package com.example.andylau96.res.Main;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.andylau96.res.R;
import com.example.andylau96.res.DataBase.UserDataBase;

/**
 * Created by AndyLau96 on 2016/11/7.
 */
public class Login extends Activity implements View.OnClickListener {

    private Button btn_login;
    private Button btn_exit;
    private TextView user_name;
    private TextView user_pwd;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.login);
        btn_login = (Button) findViewById(R.id.login_ok);
        btn_exit = (Button) findViewById(R.id.login_exit);
        user_name= (TextView) findViewById(R.id.login_name);
        user_pwd= (TextView) findViewById(R.id.login_pwd);
        btn_login.setOnClickListener(this);
        btn_exit.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.login_ok)
        {
            Cursor cr=null;
            SQLiteDatabase db=new UserDataBase(this.getApplication()).getReadableDatabase();
            if(user_name.getText().toString().length()==0||user_pwd.getText().toString().length()==0)
                Toast.makeText(this,"请输入完整的工号和密码",Toast.LENGTH_SHORT).show();
            else {
                cr = db.rawQuery("select *from user where WorkId=" + user_name.getText().toString() + " and Password='" + user_pwd.getText().toString() + "'", null);
                if (cr.getCount() != 0) {
                    cr.moveToFirst();
                    int permission=cr.getInt(cr.getColumnIndex("Permission"));
                    int workid=cr.getInt(cr.getColumnIndex("WorkId"));
                    Intent intent = new Intent();
                    intent.putExtra("Permission",permission);
                    intent.putExtra("WorkId",workid);
                    intent.setClass(Login.this, MainActivity.class);
                    startActivity(intent);
                    cr.close();
                    super.finish();
                } else
                {
                    Toast.makeText(this, "工号或密码错误", Toast.LENGTH_SHORT).show();
                    user_pwd.setText("");
                }
                db.close();
            }
        }
        if(v.getId()==R.id.login_exit)
        {
            super.finish();
        }
    }
}